'use strict';
import React, {
    Component
} from 'react'
import ReactDOM, {
    render
} from 'react-dom'
import {
    R_header_fixed
} from './common/index'
import {
    HttpService,
    Toast,
    getBlob
} from '../Http'
import $ from 'jquery'
import {
    taskFinish
} from '../Tools'
import ConfirmBox from './Common/ConfirmBox'
import '../plugins/upload/css/cropper.css'
import '../plugins/upload/css/mui.css'

import '../plugins/upload/js/bundle'
import '../plugins/upload/js/cropper'

import imgBaby from '../img/baby/touxiang.png'
import imgTouxiang from '../img/baby/touxiang.png'
import imgNicheng from '../img/baby/nicheng.png'
import imgXingming from '../img/baby/xingming.png'
import imgXuexiao from '../img/baby/xuexiao.png'
import imgBanji from '../img/baby/banji.png'
import imgXueji from '../img/baby/xueji.png'
import imgShengri from '../img/baby/shengri.png'
import imgShengao from '../img/baby/shengao.png'
import imgTizhong from '../img/baby/tizhong.png'
import imgXingbie from '../img/baby/xingbie.png'

export default class Baby extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    //构造函数
    constructor(props) {
        super(props);
        this.sex = '';
        this.babyInfo = {
            test: 1,
            headimg: ''
        };
        this.babyInfoStr = '';
    }

    //页面进入前
    componentWillMount() {
        HttpService.query({
            url: '/app/object/getBabyJxt',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid
                //weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10038') {
                    this.babyInfo = res.data;
                    this.setState({
                        sex: res.data.sex
                    })
                } else {
                    Toast.toast('获取设备信息失败');
                }
            })
        })
    }

    //页面加载完毕
    componentDidMount() {
        let babyInfo = this.babyInfo;
        this.refs.babyname.value = babyInfo.babyname || '';
        this.refs.birthday.value = babyInfo.birthday || '';
        this.refs.height.value = babyInfo.height + 'CM' || '';
        this.refs.sex.value = babyInfo.sex || '';
        this.refs.studentid.value = babyInfo.studentid || '';
        this.refs.studentname.value = babyInfo.studentname || '';
        //this.refs.teacherclassname.value = babyInfo.teacherclassname || '';
        //this.refs.teacherschoolname.value = babyInfo.teacherschoolname || '';
        this.refs.weight.value = babyInfo.weight + 'KG' || '';
        this.babyInfoStr = babyInfo.babyname + babyInfo.birthday + babyInfo.height + babyInfo.studentid + babyInfo.studentname + babyInfo.weight + babyInfo.sex;
    }

    setBabyInfo() {
        let babyInfo = {};
        babyInfo.token = localStorage.appToken;
        babyInfo.babyid = this.props.params.babyid;
        babyInfo.weixinclient = true;
        babyInfo.babyname = this.refs.babyname.value;
        babyInfo.studentname = this.refs.studentname.value;
        babyInfo.birthday = this.refs.birthday.value.replace(/\//g, '-');
        babyInfo.height = parseInt(this.refs.height.value);
        babyInfo.sex = this.refs.sex.value;
        babyInfo.studentid = this.refs.studentid.value;
        babyInfo.weight = parseInt(this.refs.weight.value);
        if (this.babyInfoStr == babyInfo.babyname + babyInfo.birthday + babyInfo.height + babyInfo.studentid + babyInfo.studentname + babyInfo.weight + babyInfo.sex) {
            this.context.router.goBack();
            return;
        }

        HttpService.query({
            url: '/app/object/modifyBabyInfo',
            data: babyInfo,
            success: (res => {
                localStorage.setDevice = 1;
                if (res.code == '10042') {
                    this.babyInfo = res.data;
                    Toast.toast('修改宝贝信息成功');
                } else {
                    Toast.toast('保存宝贝信息失败');
                }
                this.context.router.goBack();
            })
        });
    }
    //点击选择男女
    sltSexHandle() {
        document.getElementById('sltsexpeal').style.display = 'block'
        document.getElementById('sltsexlist').style.display = 'block'
    }
    sltSexList(sex) {
        document.getElementById('sltsexlist').style.display = 'none'
        document.getElementById('sltsexpeal').style.display = 'none'
        this.refs.sex.value = sex;
        this.setState({
            sex
        });
    }

    //转化为数字
    floatInt(e) {
        if (e.target.value == '')
            return;
        e.target.value = parseInt(e.target.value);
    }

    //设置身高体重为数字
    setNumber(e) {
        let unit = 'KG'
        let value = e.target.value;
        if (value == '')
            return;
        value = parseInt(value);

        if (isNaN(value)) {
            e.target.value = '';
            Toast.toast('请输入正确的数字');
            return;
        }
        if (e.target.getAttribute('name') == 'height') {
            unit = 'CM'
            if (value > 300) {
                Toast.toast('请输入正常的身高');
                value = 300;
            }
        } else {
            if (value > 200) {
                Toast.toast('请输入正常的体重');
                value = 200;
            }
        }
        e.target.value = value + unit;
    }

    //字符限制
    limitSize(e) {
        if (e.target.value.length > 5) {
            Toast.toast('最多5位字符');
            e.target.value = e.target.value.substr(0, 5);
        }
    }
    //图片剪切
    //取消剪切
    cancelShear() {
        document.getElementById('showEdit').style.display = 'none'
        document.getElementById('showResult').style.display = 'block'
    }
    //确认剪切
    confirmShear() {
        document.getElementById('showResult').style.display = 'none'
        document.getElementById('showEdit').style.display = 'none'
        var imgObj = document.getElementById('report').children[0];
        var dataURL = $(imgObj).cropper('getCroppedCanvas');
        var baseStr = dataURL.toDataURL("image/jpeg", 0.1);
        document.getElementById('upimg1').setAttribute('src', baseStr);
        var text = window.atob(baseStr.split(',')[1]);
        var buffer = new Uint8Array(baseStr.length);
        var pecent = 0,
            loop = null;
        for (var i = 0; i < text.length; i++) {
            buffer[i] = text.charCodeAt(i);
        }
        var imgType = baseStr.split(';')[0].split(':')[1];
        var blob = getBlob([buffer], imgType);
        let data = new FormData();
        data.append('token', localStorage.appToken);
        data.append('babyid', this.props.params.babyid);
        data.append('headimg', blob, 'test.jpg');
        console.log(blob);
        let rct = this;
        $.ajax({
            url: '/app/object/saveHeadImg',
            type: 'POST',
            data: data,
            cache: false,
            contentType: false, //不可缺
            processData: false, //不可缺
            success: function(res) {
                localStorage.setDevice = 1;
                Toast.toast(res.msg);
                taskFinish('上传头像', (status, config) => {
                    if (status) {
                        rct.config = config;
                        rct.setState({
                            show: 1
                        })
                    }
                })
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Toast.toast('网络连接错误');
            }
        })
    }

    //剪切图片
    cutImg() {
        document.getElementById('showResult').style.display = 'none'
        document.getElementById('showEdit').style.display = 'block'
        var imgObj = document.getElementById('report').children[0];
        $(imgObj).cropper({
            aspectRatio: 1 / 1,
            autoCropArea: 1,
            strict: true,
            guides: false,
            center: true,
            highlight: false,
            dragCrop: false,
            cropBoxMovable: false,
            cropBoxResizable: false,
            zoom: -4,
            checkImageOrigin: true,
            background: false,
            minContainerHeight: 100,
            minContainerWidth: 100
        });
    }
    //最后处理
    doFinish(rst) {
        document.getElementById('report').innerHTML = '<img src="' + rst.base64 + '" style="width: 100%;height:100%">'
        this.cutImg();
    }
    //选择图片
    sltPic(e) {
        var rct = this;
        var that = e.target;
        lrz(that.files[0], {
            width: 600,
            height: 600,
            quality: 0.7
        }).then(function(rst) {
            //console.log(rst);
            rct.doFinish(rst);
            return rst;
        }).then(function(rst) {
            // 这里该上传给后端啦
            // 伪代码：ajax(rst.base64)..
            return rst;
        }).then(function(rst) {
            // 如果您需要，一直then下去都行
            // 因为是Promise对象，可以很方便组织代码 \(^o^)/~
        }).catch(function(err) {
            // 万一出错了，这里可以捕捉到错误信息
            // 而且以上的then都不会执行
            Toast.toast(err);
        }).always(function() {
            // 不管是成功失败，这里都会执行
        });
    }
    render() {
        const babyInfo = this.babyInfo
        const sex = this.state.sex
        return <div className="babybox">
            <R_header_fixed title="宝贝信息" left="1" newfn={this.setBabyInfo.bind(this)}/>
            <ul className='babylist'>
                <li>
                    <img className='left' src={imgTouxiang}/>
                    <label className='txrbar' for="upcard1">
                        <label>头像</label>
                        <label className='babyhead'>
                            <input className='upcard hidden' name='headimg' type="file" id="upcard1" accept="image/*" onChange={this.sltPic.bind(this)}/>
                            <img id='upimg1' src={babyInfo.headimg
                                ? '/media' + babyInfo.headimg
                                : imgBaby}/>
                        </label>
                    </label>
                </li>
                <li>
                    <img className='left' src={imgNicheng}/>
                    <div className='txrbar'>
                        <label>昵称</label>
                        <input type='text' placeholder='无' ref='babyname' onChange={this.limitSize.bind(this)}/>
                    </div>
                </li>
                <li className="mtop">
                    <img className='left' src={imgXingming}/>
                    <div className='txrbar'>
                        <label>姓名</label>
                        <input type='text' placeholder='无' ref='studentname' onChange={this.limitSize.bind(this)}/>
                    </div>
                </li>
                <li>
                    <img className='left' src={imgXuexiao}/>
                    <div className='txrbar'>
                        <label>学校</label>
                        <input type='button' className='disabled' value={babyInfo.schoolname}/>
                    </div>
                </li>
                <li>
                    <img className='left' src={imgBanji}/>
                    <div className='txrbar'>
                        <label>班级</label>
                        <input type='button' className='disabled' value={babyInfo.grade}/>
                    </div>
                </li>
                <li>
                    <img className='left' src={imgXueji}/>
                    <div className='txrbar'>
                        <label>学籍号</label>
                        <input type='tel' placeholder='无' ref='studentid'/>
                    </div>
                </li>
                <li className="mtop">
                    <img className='left' src={imgShengri}/>

                    <label className='txrbar'>
                        <label>生日</label>
                        {navigator.userAgent.toLowerCase().match(/Android/i) == 'android'
                            ? <input type='date' placeholder='无' ref='birthday' id='birthday2'/>
                            : <input type='date' placeholder='无' ref='birthday' id='birthday'/>
}

                    </label>
                </li>
                <li>
                    <img className='left' src={imgShengao}/>

                    <div className='txrbar'>
                        <label>身高</label>
                        <input type='tel' pattern="[0-9]*" placeholder='无' ref='height' name='height' onBlur={this.setNumber.bind(this)} onFocus={this.floatInt.bind(this)}/>
                    </div>
                </li>
                <li>
                    <img className='left' src={imgTizhong}/>
                    <div className='txrbar'>
                        <label>体重</label>
                        <input type='tel' placeholder='无' ref='weight' name='weight' onBlur={this.setNumber.bind(this)} onFocus={this.floatInt.bind(this)}/>
                    </div>
                </li>
                <li>
                    <img className='left' src={imgXingbie}/>
                    <div className='txrbar' onClick={this.sltSexHandle.bind(this)}>
                        <label>性别</label>
                        <input type='button' ref='sex' readOnly='readOnly' value={sex}/>
                    </div>
                </li>
            </ul>
            <div id='sltsexpeal' onClick={this.sltSexList.bind(this, sex)}></div>
            <ul id='sltsexlist'>
                <li className={sex == '男'
                    ? 'active'
                    : ''} onClick={this.sltSexList.bind(this, '男')}>男</li>
                <li className={sex == '女'
                    ? 'active'
                    : ''} onClick={this.sltSexList.bind(this, '女')}>女</li>
            </ul>
            <div className='publicbox'>
                <input type='button' className='publicbtn' value='保存信息' onClick={this.setBabyInfo.bind(this)} />
            </div>
            <div id="showResult">
                <div id="changeAvatar">
                    <img/>
                </div>
            </div>
            <div id="showEdit" className='showEdit'>
                <button className="cencelbtn" data-mui-style="fab" onClick={this.cancelShear.bind(this)}>取消</button>
                <button className="confirmbtn" data-mui-style="fab" data-mui-color="primary" onClick={this.confirmShear.bind(this)}>确定</button>
                <div id="report">
                    <img/>
                    <span className="cropper-center"></span>
                    <span className="cropper-dashed dashed-h cropper-hidden"></span>
                    <span className="cropper-dashed dashed-v cropper-hidden"></span>
                    <span className="cropper-face cropper-invisible cropper-move"></span>
                    <span className="cropper-line line-e cropper-hidden" data-action="e"></span>
                    <span className="cropper-line line-n cropper-hidden" data-action="n"></span>
                    <span className="cropper-line line-w cropper-hidden" data-action="w"></span>
                    <span className="cropper-line line-s cropper-hidden" data-action="s"></span>
                    <span className="cropper-point point-e cropper-hidden" data-action="e"></span>
                    <span className="cropper-point point-n cropper-hidden" data-action="n"></span>
                    <span className="cropper-point point-w cropper-hidden" data-action="w"></span>
                    <span className="cropper-point point-s cropper-hidden" data-action="s"></span>
                    <span className="cropper-point point-ne cropper-hidden" data-action="ne"></span>
                    <span className="cropper-point point-nw cropper-hidden" data-action="nw"></span>
                    <span className="cropper-point point-sw cropper-hidden" data-action="sw"></span>
                    <span className="cropper-point point-se cropper-hidden" data-action="se"></span>
                </div>
            </div>
            <ConfirmBox config={this.config} show={this.state.show} sigle='1'/>

        </div>
    }
}
